package org.mlf.fsyq.demo.wordcount;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author chenjiahao
 * 有界流处理：获取有限的数据源进行处理
 */
public class BoundedStreamWordCount {

    public static void main(String[] args) throws Exception {
        // 1.创建流式的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 2.读取文件
        DataStreamSource<String> lineDataStreamSource = env.readTextFile("input/words.txt");

        // 3.转换计算
        SingleOutputStreamOperator<Tuple2<String, Long>> wordAndOneTuple = lineDataStreamSource.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words = line.split(" ");
            for (String word : words) {
                out.collect(Tuple2.of(word, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        // 4.分组
        KeyedStream<Tuple2<String, Long>, String> wordAndOneKeyedStream = wordAndOneTuple.keyBy(data -> data.f0);

        // 5.求和
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = wordAndOneKeyedStream.sum(1);

        // 6.输出
        sum.print();

        // 7.启动执行，流处理 只是定义流执行流程，需要启动流程，不停的等待数据的到来去输出
        env.execute();

        /**
         * 输出结果：
         * 7> (flink,1)
         * 3> (hello,1)
         * 5> (world,1)
         * 2> (java,1)
         * 3> (hello,2)
         * 2> (java,2)
         * 6> (no,1)
         * 3> (hello,3)
         * 可以看到与批处理不同的是，每一个单词都有一个自增的过程，hello由最开始的1到最后增加到了3
         */

    }
}
